<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ls, ss } from '@/utils/storage'
import { fetchLogin } from '@/api/index'
import { TOKEN_NAME, USER_NAME } from '@/utils/constants'
import { useChatStore } from '@/store'

interface RuleForm {
  username: string
  password: string
}
interface ResponseLogin {
  token: string
  expires_time: number
}
const router = useRouter()
const ruleFormRef = ref<FormInstance>()
const form = reactive<RuleForm>({
  username: '',
  password: '',
})

const rules = reactive<FormRules<RuleForm>>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})
const chatStore = useChatStore()
const loading = ref(false)
const signIn = async (formEl: FormInstance | undefined) => {
  if (!formEl)
    return
  await formEl.validate(async (isValid) => {
    window.console.log(isValid)
    if (isValid) {
      try {
        const res = await fetchLogin<ResponseLogin>(form)
        window.console.log(res, 'login----')
        // const res = {
        // 	data: {
        // 		token: '1234',
        // 		expires_time: 7200,
        // 	},
        // }
        const oldUserName = ls.get(USER_NAME)
        window.console.log(oldUserName, '****')
        if (oldUserName && oldUserName !== form.username) {
          // 清楚cookie
          ls.remove('chatStorage')
          chatStore.resetChat()
        }
        ss.set(USER_NAME, form.username)
        ls.set(TOKEN_NAME, res.data.token, { expire: res.data.expires_time })
        router.push({ name: 'Chat' })
      }
      catch (error: any) {
        ElMessage.error(error.msg)
      }
    }
  })
}
</script>

<template>
  <el-form ref="ruleFormRef" :model="form" label-position="top" size="large" :rules="rules">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="form.username" placeholder="请输入用户名" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="form.password" type="password" placeholder="请输入密码" />
    </el-form-item>
    <ElButton :loading="loading" type="primary" class="w-full" native-type="submit" @click.prevent="signIn(ruleFormRef)">
      登录
    </ElButton>
  </el-form>
</template>
